package com.mxsoft.takeaway.web.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.mxsoft.takeaway.model.User;
import com.mxsoft.takeaway.service.IUserService;
import com.mxsoft.takeaway.util.JWT;
import com.mxsoft.takeaway.util.ResponseData;
import com.mxsoft.takeaway.util.TokenDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author generator
 * @since 2018-04-27
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @GetMapping("/test")
    public Object test() {
        return userService.selectById(1);
    }

    @PostMapping(value = "/login", produces = "application/json; charset=utf-8")
    public @ResponseBody
    ResponseData login(@RequestParam("username") String username, @RequestParam("password") String password) {
        TokenDto tokenDto = new TokenDto();
        tokenDto.setUsername(username);
        tokenDto.setPassword(password);
        ResponseData responseData = ResponseData.ok();
        User user = userService.selectOne(new EntityWrapper<User>().eq("username", username).eq("is_delete", 0));
        if (null == user || !user.getPassword().equals(encryptPasswordWithSaltKey(password, user.getSalt()))) {
            return ResponseData.customerError();
        }
        tokenDto.setId(user.getId());
        //给用户jwt加密生成token
        String token = JWT.sign(tokenDto, 60L * 1000L * 30L);
        //封装成对象返回给客户端
        responseData.putDataValue("loginId", tokenDto.getId());
        responseData.putDataValue("token", token);
//        responseData.putDataValue("user", user);
        return responseData;
    }

    private String encryptPasswordWithSaltKey(String password, String saltKey) {
        MessageDigest messageDigest;
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA-256加密算法不存在");
        }
        String passwordWithSaltKey = password + saltKey;
        messageDigest.update(passwordWithSaltKey.getBytes());
        byte hashByteBuffer[] = messageDigest.digest();
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < hashByteBuffer.length; ++i) {
            String hex = Integer.toHexString(0xff & hashByteBuffer[i]);
            if (hex.length() == 1) {
                result.append('0');
            }
            result.append(hex);
        }
        return result.toString();
    }
}

